package Servlet.File;

import Server.File.updateFileServer;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/novelFileUpload")
public class novelFileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");		
		//java.io.PrintWriter out = response.getWriter();	
		String url = "novelFileUpload.jsp";
		String realPath = request.getServletContext().getRealPath("");
		if(ServletFileUpload.isMultipartContent(request)){
			//创建FileItemFactory工厂实现类
			FileItemFactory factory = new DiskFileItemFactory();
			//创建用于解析数据的工具类ServletFileUpload类
			ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

			String novelName=null;
			try {
				//解析上传的数据，得到每一个表单项FileItem
				List<FileItem> list = servletFileUpload.parseRequest(request);
				//判断每个表单项是普通类型还是上传的文件
				for(FileItem item : list){
					if(item.isFormField()){
						//普通表单项
//						System.out.println("表单项的name："+item.getFieldName());
//						//使用UTF-8解析，防止乱码
//						System.out.println("表单项的value："+item.getString("UTF-8"));
						novelName=item.getString("UTF-8");
					}else {
						//上传的文件
//						System.out.println("表单项的name："+item.getFieldName());
//						System.out.println("上传的文件名为："+item.getName());
//						//将此文件写到d盘根目录
//						item.write(new File("d:\\"+item.getName()));
						if(novelName== null ||novelName.equals(""))
							throw new Exception("novelName is null");

						updateFileServer.updateFileServer(realPath,novelName,item);
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
